package com.erp.auto.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.auto.domain.ErpAutoInfoModuleConfig;
import com.erp.auto.domain.ErpAutoModuleProductLog;
import com.ruoyi.auto.api.domain.ErpAutoSellerStoreConfig;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigMapper;
import com.ruoyi.gather.api.RemoteAeProductStatisticsService;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.gather.api.domain.dto.ProductInfoModuleDto;
import com.erp.auto.mapper.ErpAutoInfoModuleConfigMapper;
import com.erp.auto.mapper.ErpAutoModuleProductLogMapper;
import com.erp.auto.service.ErpAutoInfoModuleConfigService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.order.api.RemoteErpChildOrderService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import feign.codec.DecodeException;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * 信息模块自动化配置
 *
 * @author WXX
 * @date 2023-12-28 10:27:55
 */
@Service
@AllArgsConstructor
public class ErpAutoInfoModuleConfigServiceImpl implements ErpAutoInfoModuleConfigService {

    private final ErpAutoInfoModuleConfigMapper erpAutoInfoModuleConfigMapper;
    private final ErpAutoSellerStoreConfigMapper sellerStoreConfigMapper;

    private final ErpAutoModuleProductLogMapper moduleProductLogMapper;
    private final RemoteSellerStoreService sellerStoreService;
    private final RestTemplate restTemplate;
    private final RemoteAeProductStatisticsService aeProductStatisticsService;
    private final RemoteSellerStoreProductService sellerStoreProductService;
    private final RemoteErpChildOrderService remoteErpChildOrderService;

    @Override
    public int saveConfig(ErpAutoInfoModuleConfig config) {
        int save;
        if (config.getId() == null) {
            config.setCreateTime(new Date());
            save = erpAutoInfoModuleConfigMapper.insert(config);
        }
        else {
            save = erpAutoInfoModuleConfigMapper.updateById(config);
        }
        return save;
    }

    @Override
    public List<ErpAutoInfoModuleConfig> getList(ErpAutoInfoModuleConfig moduleConfig) {
        LambdaQueryWrapper<ErpAutoInfoModuleConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(moduleConfig.getStatus() != null, ErpAutoInfoModuleConfig::getStatus, moduleConfig.getStatus());
        return erpAutoInfoModuleConfigMapper.selectList(queryWrapper);
    }

    @Override
    public ErpAutoInfoModuleConfig selectById(Long id) {
        return erpAutoInfoModuleConfigMapper.selectById(id);
    }

    @Override
    public int updateStatusById(Long id) {
        ErpAutoInfoModuleConfig moduleConfig = erpAutoInfoModuleConfigMapper.selectById(id);
        if (moduleConfig.getStatus() == 0) {
            moduleConfig.setStatus(1);
        }
        else {
            moduleConfig.setStatus(0);
        }
        return erpAutoInfoModuleConfigMapper.updateById(moduleConfig);
    }

    @Override
    public void executeCreate(ErpAutoInfoModuleConfig moduleConfig) {
//        List<ErpAutoInfoModuleConfig> infoModuleConfig = getInfoModuleConfig(moduleConfig);
//        List<ErpAutoInfoModuleConfig> infoModuleConfig = erpAutoInfoModuleConfigMapper.selectList(new LambdaQueryWrapper<ErpAutoInfoModuleConfig>().ne(ErpAutoInfoModuleConfig::getId, 1783044426080968706L));
//        for (ErpAutoInfoModuleConfig moduleConfig : infoModuleConfig) {
            executeCreateModule(moduleConfig);
//        }
    }

    /**
     * 创建模块
     */
    public R<Object> executeCreateModule(ErpAutoInfoModuleConfig moduleConfig) {
        Long configId = moduleConfig.getId();
        ErpAutoModuleProductLog log = new ErpAutoModuleProductLog();
        List<ErpAutoModuleProductLog> logList = new ArrayList<>();

        Long storeId = moduleConfig.getStoreId();
        String cookie = sellerStoreService.getCookieByStoreId(storeId);
        moduleConfig.setCookie(cookie);
        // 删除过期模块
        executeDeleteModule(moduleConfig);

        // 判断应该创建模块的数量
        JSONObject moduleNumsBody = getModule(cookie, null, null);
        int moduleCount = 50; // 待创建模块数量
        if (moduleNumsBody.getInteger("code") == 200) {
            JSONObject data = moduleNumsBody.getJSONObject("data");
            // 获取到module_id
            int size = 0;
            JSONObject dataObject = data.getJSONObject("data");
            if (dataObject.size() != 0) {
                JSONArray dataArray = dataObject.getJSONObject("data").getJSONArray("dataSource");
                size = dataArray.size();
            }
            if (size == moduleCount) {
                log.setStatus(1);
                log.setRemark("执行成功，模块已满50，不再创建模块");
                log.setConfigId(configId);
                log.setCreateTime(new Date());
                logList.add(log);
                saveModuleLog(logList);
                return R.ok();
            }
            else {
                moduleCount = moduleCount - size;
            }

            Integer productSource = moduleConfig.getProductSource();
            // 先根据创建顺序找到商品
            String createSort = moduleConfig.getCreateSort();
            List<String> sort = Arrays.stream(createSort.split(",")).collect(Collectors.toList());
            List<ProductInfoModuleDto> productInfoModuleDtoList = null;
            try {
                productInfoModuleDtoList = aeProductStatisticsService.getProductRankByStoreId(sort.get(0), productSource, storeId, moduleCount);
            }catch (DecodeException e) {
                return R.fail("数据库线程池断开连接");
            }

            // 创建
            Integer productOut = moduleConfig.getProductOut();
            Integer productVisitor = moduleConfig.getProductVisitor();
            for (ProductInfoModuleDto productInfoModuleDto : productInfoModuleDtoList) {
                Long productId = productInfoModuleDto.getProductId();
                // 判断商品是否已绑定信息模块
                Long count = moduleProductLogMapper.selectCount(new LambdaQueryWrapper<ErpAutoModuleProductLog>().eq(ErpAutoModuleProductLog::getProductId, productId));
                if (count >= 1) {
                    continue;
                }
                // 找 8 主 出单，从 找未出单或访客低的
                Integer type = productInfoModuleDto.getType();
                List<Long> productIds = new ArrayList<>();
                if (type == 0) {
                    productIds = aeProductStatisticsService.getProductsRankByPrimary(productId, productSource, productOut);
                }
                else if (type == 1) {
                    productIds = aeProductStatisticsService.getProductsRankByPrimary(productId, productSource, productVisitor);
                }
                // 判断是否达到创建模块的要求
                Integer productCount = moduleConfig.getProductCount();
                if (productIds.size() < productCount) {
                    // 小于不创建
                    continue;
                }
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < productIds.size(); j++) {
                    if (j > 0) {
                        sb.append(",");
                    }
                    sb.append(productIds.get(j));
                }
                String moduleName = new Date().getTime() + "";
                JSONObject moduleJson = createModule(sb.toString(), cookie, moduleName);
                if (moduleJson != null) {
                    if (moduleJson.getInteger("code") != 200) {
                        String msg = moduleJson.getString("msg");
                        // 保存错误信息
                        log = new ErpAutoModuleProductLog();
                        log.setConfigId(configId);
                        log.setModuleName("");
                        log.setRemark(msg);
                        log.setCreateTime(new Date());
                        log.setProductSon("");
                        log.setStatus(0);
                        logList.add(log);
                    }
                    else {
                        // 给 moduleCount + 1
                        List<Long> updateProduct = productIds;
                        updateProduct.add(productId);
                        sellerStoreProductService.updateModuleCount(updateProduct);

                        // 获取到module_id
                        JSONObject module = getModule(cookie, moduleName, sb.toString());
                        JSONArray dataArray = module.getJSONObject("data").getJSONObject("data").getJSONObject("data").getJSONArray("dataSource");
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject jsonObject = dataArray.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            if (moduleName.equals(name)) {
                                Long moduleId = jsonObject.getLong("id");
                                log.setModuleId(moduleId);
                                // 关联商品和模块
                                Map<String, Object> relationMap = new HashMap<>();
                                relationMap.put("cookie_str", cookie);
                                relationMap.put("productIds", productId.toString());
                                relationMap.put("moduleId", moduleId.toString());
                                relationMap.put("type", "top");
                                ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000/detailmodule/relation", relationMap, String.class);
                                System.out.println(responseEntity.getBody());
                                break;
                            }
                        }
                        // 成功了保存关联关系
                        log.setConfigId(configId);
                        log.setModuleName(moduleName);
                        log.setCreateTime(new Date());
                        log.setProductSon(sb.toString());
                        log.setProductId(productId);
                        log.setStatus(1);
                        logList.add(log);
                        log = new ErpAutoModuleProductLog();
                    }
                }
            }
            saveModuleLog(logList);
        }
        return R.ok();
    }

    private void executeDeleteModule(ErpAutoInfoModuleConfig erpAutoInfoModuleConfig) {

        LocalDateTime currentDateTime = LocalDateTime.now();
        Long configId = erpAutoInfoModuleConfig.getId();
        Integer modelValidity = erpAutoInfoModuleConfig.getModelValidity();
        Integer modelReplace = erpAutoInfoModuleConfig.getModelReplace();
        Long storeId = erpAutoInfoModuleConfig.getStoreId();
        String cookie = erpAutoInfoModuleConfig.getCookie();
        // 获取按创建时间正序排列的模块
        List<ErpAutoModuleProductLog> erpAutoModuleProductLogList = moduleProductLogMapper.selectList(new LambdaQueryWrapper<ErpAutoModuleProductLog>()
                .eq(ErpAutoModuleProductLog::getConfigId, configId)
                .isNotNull(ErpAutoModuleProductLog::getModuleId)
                .isNotNull(ErpAutoModuleProductLog::getModuleName)
                .orderByAsc(ErpAutoModuleProductLog::getCreateTime));
        for (ErpAutoModuleProductLog erpAutoModuleProductLog : erpAutoModuleProductLogList) {
            // 超出对应天数的判断（1+8）商品是否出单
            Date createTime = erpAutoModuleProductLog.getCreateTime();
            boolean validity = overModelValidity(createTime, currentDateTime, modelValidity);
            if (validity) {
                // 判断商品是否近些天未出单
                Long productId = erpAutoModuleProductLog.getProductId();
                String productSon = erpAutoModuleProductLog.getProductSon();
                String productIds = productId + "," + productSon;
                Map<String, Object> map = new HashMap<>();
                map.put("storeId", storeId);
                map.put("modelReplace", modelReplace);
                map.put("productIds", productIds);
                Boolean placed = remoteErpChildOrderService.isOrderPlacedForProduct(productIds, modelReplace);

                if (!placed) {
                    // 没有出单，删除模块
                    Map<String, Object> deleteMap = new HashMap<>();
                    // 获取到cookie
                    deleteMap.put("cookie_str", cookie);
                    deleteMap.put("moduleId", erpAutoModuleProductLog.getModuleId().toString());
                    ResponseEntity<String> response = restTemplate.postForEntity("http://47.94.131.193:8000/detailmodule/delete", deleteMap, String.class);
                    String body1 = response.getBody();
                    JSONObject jsonObject1 = JSONObject.parseObject(body1);
                    Integer code = jsonObject1.getInteger("code");
                    if (code == 200) {
//                        erpAutoModuleProductLog.setDelFlag(2);
//                        erpAutoModuleProductLog.setUpdateTime(new Date());
//                        moduleProductLogMapper.updateById(erpAutoModuleProductLog);
                        moduleProductLogMapper.deleteById(erpAutoModuleProductLog);
                    }
                }
            }
        }
    }

    /**
     * 获取待执行的自动化模块配置
     *
     * @return list
     */
    public List<ErpAutoInfoModuleConfig> getInfoModuleConfig(ErpAutoInfoModuleConfig moduleConfig) {
        // 先获取店铺状态有效的
//        List<ErpAutoInfoModuleConfig> list = new ArrayList<>();
//        List<ErpAutoSellerStoreConfig> sellerStoreConfigList = sellerStoreConfigMapper.getValidList();
//        for (ErpAutoSellerStoreConfig erpAutoSellerStoreConfig : sellerStoreConfigList) {
            List<ErpAutoInfoModuleConfig> infoModuleConfigList = erpAutoInfoModuleConfigMapper
                    .selectList(new LambdaQueryWrapper<ErpAutoInfoModuleConfig>()
                            .eq(ErpAutoInfoModuleConfig::getStatus, 1)
                            .eq(moduleConfig.getId() != null, ErpAutoInfoModuleConfig::getId, moduleConfig.getId())
                            .eq(moduleConfig.getStoreId() != null, ErpAutoInfoModuleConfig::getStoreId, moduleConfig.getStoreId()));
//            list.addAll(infoModuleConfigList);
//        }
        return infoModuleConfigList;
    }
    // 只能查全部
    private JSONObject getModule(String cookie, String moduleName, String sb) {
        Map<String, Object> map = new HashMap<>();
        map.put("cookie_str", cookie);
        map.put("productIds", sb);
        map.put("moduleName", moduleName);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity("http://47.94.131.193:8000/detailmodule/get", map, JSONObject.class);
        return response.getBody();
    }

    private JSONObject createModule(String sb, String cookie, String moduleName) {
        Map<String, Object> map = new HashMap<>();
        map.put("cookie_str", cookie);
        map.put("productIds", sb);
        map.put("moduleName", moduleName);
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000/detailmodule/add", map, JSONObject.class);
        return responseEntity.getBody();
    }

    void saveModuleLog(List<ErpAutoModuleProductLog> list) {

        for (ErpAutoModuleProductLog moduleProductLog : list) {
            if (moduleProductLog.getModuleId() == null) {
                System.out.println(moduleProductLog.getModuleName() + "出现");
            }
            moduleProductLogMapper.insert(moduleProductLog);
        }

    }

    private boolean overModelValidity(Date startTime, LocalDateTime endTime, Integer modelValidity) {
        LocalDateTime startLocal = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
        long between = ChronoUnit.DAYS.between(startLocal, endTime);
        return between >= modelValidity;
    }

    @Override
    public void delect(ErpAutoInfoModuleConfig moduleConfig) {
        List<ErpAutoInfoModuleConfig> infoModuleConfig = getInfoModuleConfig(moduleConfig);
        for (ErpAutoInfoModuleConfig config : infoModuleConfig) {
            Long storeId = config.getStoreId();
            String cookie = sellerStoreService.getCookieByStoreId(storeId);
            // 获取到
            JSONObject module = getModule(cookie, null, null);
            
            Integer code = module.getInteger("code");
            if (code != 200)
                continue;
            JSONObject jsonObject1 = module.getJSONObject("data").getJSONObject("data");
            if (jsonObject1.size() == 0)
                continue;
            JSONArray dataArray = jsonObject1.getJSONObject("data").getJSONArray("dataSource");
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject jsonObject = dataArray.getJSONObject(i);
                Long id = jsonObject.getLong("id");
                String name = jsonObject.getString("name");
                if (!name.matches("\\d+") && name.length() != 13) {
                    continue;
                }
                String time = jsonObject.getString("time");
//                if ("2024-04-19".equals(time)) {
                    // 删除
                    map.put("cookie_str", cookie);
                    map.put("moduleId", id.toString());
                    ResponseEntity<String> response = restTemplate.postForEntity("http://47.94.131.193:8000/detailmodule/delete", map, String.class);
//                }
            }
        }
    }
}
